package org.grayrabbit.cloud.core.rpc;

import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cloud.core.mina.RemoteChannel;


public class LocalChannelFactory implements ChannelFactory<Result> {
	private ConcurrentMap<String, RemoteChannel> remotes;
	private ConcurrentMap<String, Queue<LocalChannel>> channels;
	public LocalChannelFactory(){
		remotes =  new ConcurrentHashMap<String, RemoteChannel>();
		channels = new ConcurrentHashMap<String, Queue<LocalChannel>>();
	}
	public Channel<Result> alloc(String url)
			throws URLException, ChannelException {
		return alloc_i(url);
	}

	
	public void free(Channel<Result> channel) throws ChannelException {

	}

	private Channel<Result> alloc_i(String url) {
		RemoteChannel remote =  remotes.get(url);
		if(remote==null){
	        String[] arr = url.split(":");
	        int port = 1053;
	        String host = "127.0.0.1";
	        if(StringUtils.isNotBlank(arr[0])){
	        	host = arr[0];
	        }
	        if(StringUtils.isNotBlank(arr[1])){
	        	port = Integer.parseInt(arr[1]);
	        }
			remote = new RemoteChannel(host,port);
		}
		Queue<LocalChannel> queue = channels.get(url);
		if(queue==null){
			queue = new ConcurrentLinkedQueue<LocalChannel>();
			this.channels.putIfAbsent(url, queue);
			queue = this.channels.get(url);
		}
		LocalChannel localChannel = queue.poll();
		if(localChannel==null){
			localChannel = new LocalChannel(remote);
		}
		return localChannel;
	}

}
